package com.gagakuai.bind;

import com.gagakuai.session.SqlSession;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/*
 * @program: common-starters
 * @description: mapper代理工厂
 * @author: houhong
 * @create: 2023-06-28 23:39
 */
public class MapperProxyFactory<T> {

    private final Class<T> mapperInterface;

    private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<>();

    public MapperProxyFactory(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;
    }

    public Class<T> getMapperInterface() {
        return mapperInterface;
    }

    public Map<Method, MapperMethod> getMethodCache() {
        return methodCache;
    }

    /*
     * @param mapperProxy:代理类
     * @return {@link T}
     * @Author houhong
     * @Description 生成代理类
     * @Date 11:42 下午 2023/6/28
     */
    protected T newInstance(MapperProxy<T> mapperProxy) {
            return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, mapperProxy);
    }

    /*
     * @param sqlSession: sqlSession
     * @return {@link T}
     * @Author houhong
     * @Description 生成代理类
     * @Date 11:42 下午 2023/6/28
     */
    public T newInstance(SqlSession sqlSession) {
        final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
        return newInstance(mapperProxy);

    }

}